﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.Host;
using DWF.Studio.ISerivces;
using DWF.Studio.Project;
using DWF.Studio.RobotCommunication;
using DWF.Studio.Script;
using DWF.Studio.Services;
using DWF.Studio.Share.Log;
using DWF.Studio.Share.Utils;
using Microsoft.Win32;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// 工程浏览器控件
    /// </summary>
    public partial class UCtrlProjectExplorer : UserControl
    {
        private ObservableCollection<ProjectNode> _nodeCollection = new ObservableCollection<ProjectNode>();

        /// <summary>
        /// 工程管理器
        /// </summary>
        private ProjectManager _projectManager = null;

        private IExecutionService _executionService = null;

        public UCtrlProjectExplorer()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            _projectManager = ProjectManager.Instance;
            this._executionService = ExecutionService.Instance;
            this.tvProject.ItemsSource = _nodeCollection;

            GlobalActionHandler.ProjectOpen += openProject;
            GlobalActionHandler.ProjectCreate += createProject;
            GlobalActionHandler.ProjectClosing += closeProject;
            GlobalActionHandler.ProjectDeploy += projectDeploy;

            GlobalActionHandler.RepairSnippetActivity += repairSnippetActivity;
            GlobalActionHandler.CheckSnippetActivity += checkSnippetActivity;
        }

        /// <summary>
        /// 鼠标右键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var tvItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
            if (tvItem != null)
            {
                //if (tvItem.ContextMenu == null)
                //{        
                ProjectNode node = tvItem.DataContext as ProjectNode;
                if (node.NodeType == EProjectNodeType.Project)
                {
                    tvItem.ContextMenu = getProjectInfoRightMenu(tvItem.DataContext as ProjectInfo);//设置工程节点菜单
                }
                else if (node.NodeType == EProjectNodeType.Dependencies)
                {
                    tvItem.ContextMenu = getProjectDependencyRightMenu(tvItem.DataContext as ProjectDependencies);//设置工程节点菜单
                }
                else if (node.NodeType == EProjectNodeType.Package)
                {
                    tvItem.ContextMenu = getProjectPackageRightMenu(tvItem.DataContext as ProjectPackage);//设置工程节点菜单
                }
                else if (node.NodeType == EProjectNodeType.Folder)
                {
                    tvItem.ContextMenu = getFolderItemRightMenu(tvItem.DataContext as ProjectFolder);//设置文件夹节点菜单
                }
                else if (node.NodeType == EProjectNodeType.File)
                {
                    tvItem.ContextMenu = getFileItemRightMenu(tvItem.DataContext as ProjectFile);//设置文件节点菜单
                }
                //}

                tvItem.Focus();
                e.Handled = true;
            }
        }

        /// <summary>
        /// 获取工程节点菜单
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private ContextMenu getProjectInfoRightMenu(ProjectInfo project)
        {
            var menu = new ContextMenu();

            MenuItem itembuild = new MenuItem();
            itembuild.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Publish");
            itembuild.Command = CustomCommands.CmdProjectPublish;
            itembuild.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Publish.png", UriKind.Relative))
            };
            menu.Items.Add(itembuild);

            menu.Items.Add(new Separator());

            MenuItem itemrun = new MenuItem();
            itemrun.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Run");
            itemrun.Command = CustomCommands.CmdScriptRun;
            itemrun.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Run.png", UriKind.Relative))
            };
            menu.Items.Add(itemrun);

            MenuItem itemdebug = new MenuItem();
            itemdebug.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Debug");
            itemdebug.Command = CustomCommands.CmdScriptDebug;
            itemdebug.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Debug.png", UriKind.Relative))
            };
            menu.Items.Add(itemdebug);

            MenuItem itemstop = new MenuItem();
            itemstop.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Stop");
            itemstop.Command = CustomCommands.CmdScriptStop;
            itemstop.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Stop.png", UriKind.Relative))
            };
            menu.Items.Add(itemstop);

            menu.Items.Add(new Separator());

            MenuItem itemopen = new MenuItem();
            itemopen.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_OpenFolder");
            itemopen.CommandParameter = project.FullName;
            itemopen.Command = CustomCommands.CmdOpenFolder;
            itemopen.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/OpenFolder.png", UriKind.Relative))
            };
            menu.Items.Add(itemopen);

            menu.Items.Add(new Separator());

            MenuItem itemproperty = new MenuItem();
            itemproperty.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Property");
            itemproperty.Command = CustomCommands.CmdOpenProjectProperty;
            itemproperty.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Property.png", UriKind.Relative))
            };
            menu.Items.Add(itemproperty);

            //工程参数
            MenuItem itemparams = new MenuItem();
            itemparams.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Param");
            itemparams.Command = CustomCommands.CmdOpenProjectParams;
            itemparams.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Param.png", UriKind.Relative))
            };
            menu.Items.Add(itemparams);

            menu.Items.Add(new Separator());

            MenuItem itemclose = new MenuItem();
            itemclose.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_Close");
            itemclose.Command = CustomCommands.CmdCloseProject;
            itemclose.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Close.png", UriKind.Relative))
            };
            menu.Items.Add(itemclose);

            return menu;
        }

        /// <summary>
        /// 工程依赖节点菜单
        /// </summary>
        /// <param name="projectDependency"></param>
        /// <returns></returns>
        private ContextMenu getProjectDependencyRightMenu(ProjectDependencies projectDependency)
        {
            var menu = new ContextMenu();

            MenuItem itemPackageManagement = new MenuItem();
            itemPackageManagement.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectDependency_PackageManagement");
            itemPackageManagement.Command = CustomCommands.CmdPackageManagement;
            itemPackageManagement.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/PackageManagement.png", UriKind.Relative))
            };
            menu.Items.Add(itemPackageManagement);

            var packageInfos = _projectManager.GetDependOnPackageInfos();
            MenuItem itemPackageRepair = new MenuItem();
            itemPackageRepair.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectDependency_RepairPackage");
            itemPackageRepair.IsEnabled = packageInfos.Any(item => !item.IsInstalled);
            itemPackageRepair.CommandParameter = packageInfos.Where(item => !item.IsInstalled).ToList();
            itemPackageRepair.Command = CustomCommands.CmdRepairPackages;
            itemPackageRepair.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/RepairPackage.png", UriKind.Relative))
            };
            menu.Items.Add(itemPackageRepair);

            MenuItem itemcReloadProject = new MenuItem();
            itemcReloadProject.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectInfo_ReloadPackage");
            itemcReloadProject.Command = CustomCommands.CmdReloadPackage;
            itemcReloadProject.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/ReloadPackage.png", UriKind.Relative))
            };
            menu.Items.Add(itemcReloadProject);

            return menu;
        }

        /// <summary>
        /// 工程依赖包菜单
        /// </summary>
        /// <param name="projectPackage"></param>
        /// <returns></returns>
        private ContextMenu getProjectPackageRightMenu(ProjectPackage projectPackage)
        {
            var menu = new ContextMenu();

            MenuItem itemPackageRetrieval = new MenuItem();
            itemPackageRetrieval.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectPackage_PackageRetrieval");
            itemPackageRetrieval.CommandParameter = projectPackage;
            itemPackageRetrieval.Command = CustomCommands.CmdPackageRetrieval;
            itemPackageRetrieval.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/PackageRetrieval.png", UriKind.Relative))
            };
            menu.Items.Add(itemPackageRetrieval);

            MenuItem itemPackageRemove = new MenuItem();
            itemPackageRemove.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectPackage_UninstallPackage");
            itemPackageRemove.CommandParameter = projectPackage;
            itemPackageRemove.Command = CustomCommands.CmdUninstallPackage;
            itemPackageRemove.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/UninstallPackage.png", UriKind.Relative))
            };
            menu.Items.Add(itemPackageRemove);

            MenuItem itemPackageRepair = new MenuItem();
            itemPackageRepair.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectPackage_RepairPackage");
            itemPackageRepair.IsEnabled = !projectPackage.IsExisting;
            itemPackageRepair.CommandParameter = projectPackage;
            itemPackageRepair.Command = CustomCommands.CmdRepairPackage;
            itemPackageRepair.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/RepairPackage.png", UriKind.Relative))
            };
            menu.Items.Add(itemPackageRepair);

            return menu;
        }

        /// <summary>
        /// 获取文件夹节点菜单
        /// </summary>
        /// <param name="forder"></param>
        /// <returns></returns>
        private ContextMenu getFolderItemRightMenu(ProjectFolder forder)
        {
            var menu = new ContextMenu();

            #region 新建项
            MenuItem itemNew = new MenuItem();
            itemNew.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_New");
            itemNew.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/ProjectNew.png", UriKind.Relative))
            };

            if (forder.Name == StaticResource.ProjectSelfFile)
            {
                MenuItem itemNewSequence = new MenuItem();
                itemNewSequence.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_New_Sequence");
                itemNewSequence.CommandParameter = forder;
                itemNewSequence.Command = CustomCommands.CmdNewSequenceScript;
                itemNewSequence.Icon = new System.Windows.Controls.Image
                {
                    Source = new BitmapImage(new Uri("../Resources/Treeview/Sequence.png", UriKind.Relative))
                };
                itemNew.Items.Add(itemNewSequence);

                MenuItem itemNewFlowchart = new MenuItem();
                itemNewFlowchart.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_New_Flowchart");
                itemNewFlowchart.CommandParameter = forder;
                itemNewFlowchart.Command = CustomCommands.CmdNewFlowchartScript;
                itemNewFlowchart.Icon = new System.Windows.Controls.Image
                {
                    Source = new BitmapImage(new Uri("../Resources/Treeview/Flowchart.png", UriKind.Relative))
                };
                itemNew.Items.Add(itemNewFlowchart);
            }
            else
            {
                itemNew.IsEnabled = false;
            }
            menu.Items.Add(itemNew);

            #endregion

            #region 现有项
            MenuItem itemExisting = new MenuItem();
            itemExisting.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_Existing");
            itemExisting.CommandParameter = forder;
            itemExisting.Command = CustomCommands.CmdImportExistingScript;
            itemExisting.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Existing.png", UriKind.Relative))
            };
            menu.Items.Add(itemExisting);
            #endregion

            menu.Items.Add(new Separator());

            if (forder.Name == StaticResource.ProjectSelfImages)
            {
                MenuItem itemClearImage = new MenuItem();
                itemClearImage.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectClearImage");
                itemClearImage.CommandParameter = forder;
                itemClearImage.Command = CustomCommands.CmdClearImages;
                itemClearImage.Icon = new System.Windows.Controls.Image
                {
                    Source = new BitmapImage(new Uri("../Resources/Treeview/ProjectClearImage.png", UriKind.Relative))
                };
                menu.Items.Add(itemClearImage);

                menu.Items.Add(new Separator());
            }

            MenuItem itemopen = new MenuItem();
            itemopen.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_Existing_OpenFolder");
            itemopen.CommandParameter = forder.FullName;
            itemopen.Command = CustomCommands.CmdOpenFolder;
            itemopen.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/OpenFolder.png", UriKind.Relative))
            };
            menu.Items.Add(itemopen);

            return menu;
        }

        /// <summary>
        /// 获取文件节点菜单
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private ContextMenu getFileItemRightMenu(ProjectFile file)
        {
            var menu = new ContextMenu();

            MenuItem menuopen = new MenuItem();
            menuopen.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFile_Open");
            menuopen.CommandParameter = file;
            menuopen.Command = CustomCommands.CmdShowScript;
            menuopen.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Open.png", UriKind.Relative))
            };
            menu.Items.Add(menuopen);

            MenuItem menurename = new MenuItem();
            menurename.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFile_Rename");
            menurename.CommandParameter = file;
            menurename.Command = CustomCommands.CmdRenameScript;
            menurename.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Rename.png", UriKind.Relative))
            };
            menu.Items.Add(menurename);

            MenuItem menudel = new MenuItem();
            menudel.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFile_Delete");
            menudel.CommandParameter = file;
            menudel.Command = CustomCommands.CmdDeleteScript;
            menudel.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("../Resources/Treeview/Delete.png", UriKind.Relative))
            };
            menu.Items.Add(menudel);
            if (file.Extension == StaticResource.XamlExtension)//片段保存
            {
                menu.Items.Add(new Separator());

                MenuItem menuSaveToSnippet = new MenuItem();
                menuSaveToSnippet.Header = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFile_SaveToSnippet");
                menuSaveToSnippet.CommandParameter = file;
                menuSaveToSnippet.Command = CustomCommands.CmdSaveToSnippet;
                menuSaveToSnippet.Icon = new System.Windows.Controls.Image
                {
                    Source = new BitmapImage(new Uri("../Resources/Treeview/SaveToSnippet.png", UriKind.Relative))
                };
                menu.Items.Add(menuSaveToSnippet);
            }

            switch (file.Extension) //2021 andy 注销 支持打开其他类型文件 
            {
                case StaticResource.XamlExtension: menuopen.IsEnabled = file.IsExisting; menurename.IsEnabled = !file.IsSelf && file.IsExisting; menudel.IsEnabled = !file.IsSelf; break;
                default: menuopen.IsEnabled = true; menurename.IsEnabled = !file.IsSelf && file.IsExisting; menudel.IsEnabled = !file.IsSelf; break;
            }

            return menu;
        }

        static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
        {
            while (source != null && source.GetType() != typeof(T))
                source = VisualTreeHelper.GetParent(source);

            return source;
        }

        /// <summary>
        /// 双击工程树节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var tvitem = sender as TreeViewItem;
            if (tvitem != null)
            {
                var file = tvitem.DataContext as ProjectFile;//工程文件

                if (file != null)
                {
                    if (file.Extension == StaticResource.XamlExtension)
                    {
                        GlobalActionHandler.ScriptShow?.Invoke(new TagEventArgs<Project.ProjectFile>(file));
                    }
                    else
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(file.FullName);//打开其他文件类型文件
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(ex);
                        }
                    }
                }
                else
                {
                    var package = tvitem.DataContext as ProjectPackage;
                    if (package != null)
                    {
                        WindowPackageManagement managementWindow = new WindowPackageManagement(package.Id);
                        managementWindow.Owner = App.Current.MainWindow;
                        managementWindow.ShowDialog();
                    }
                }
            }
        }

        /// <summary>
        /// 打开工程响应
        /// </summary>
        /// <param name="e"></param>
        private void openProject(TagEventArgs<string> e)
        {
            try
            {
                _projectManager.LoadProject(e.Tag);
                this.loadProject();
            }
            catch
            {
                GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                ProjectManager.Instance.UnloadProject();
                var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                if (loaderHost != null)
                {
                    loaderHost.Unload(); //卸载控件程序域
                }
                throw;
            }
        }

        /// <summary>
        /// 创建工程响应
        /// </summary>
        /// <param name="e"></param>
        private void createProject(TagEventArgs<string, string, string, string, string> e)
        {
            try
            {
                _projectManager.CreateProject(e.Tag1, e.Tag2, e.Tag3, e.Tag4, e.Tag5);
                this.loadProject();
            }
            catch
            {
                GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                ProjectManager.Instance.UnloadProject();
                var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                if (loaderHost != null)
                {
                    loaderHost.Unload(); //卸载控件程序域
                }
                throw;
            }
        }

        /// <summary>
        /// 加载工程
        /// </summary>
        private void loadProject()
        {
            var proInfo = _projectManager.CurrentProject;
            if (proInfo != null)
            {
                proInfo.IsExpanded = true;
                _nodeCollection.Add(proInfo);

                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadProject"), proInfo.DisplayName);
                RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());

                GlobalActionHandler.ProjectOpened?.Invoke(new TagEventArgs<ProjectInfo>(proInfo));
            }
        }

        /// <summary>
        /// 关闭工程响应
        /// </summary>
        /// <param name="e"></param>
        private void closeProject(EventArgs e)
        {
            this._nodeCollection.Clear();
        }

        /// <summary>
        /// 工程生成响应
        /// </summary>
        /// <param name="e"></param>
        private void projectDeploy(EventArgs e)
        {
            if (_projectManager != null)
            {
                var issuccess = Custom.GlobalActionHandler.AllScriptSave?.Invoke(EventArgs.Empty);
                if (!issuccess.HasValue || !issuccess.Value)
                {
                    return;
                }

                var ispsass = _projectManager.ValidateScripts();
                if (!ispsass)
                {
                    Custom.GlobalActionHandler.ValidateScript?.Invoke(new TagEventArgs<string>(null));
                    return;
                }

                var windowDeploy = new WindowDeployProcess();
                windowDeploy.Owner = Window.GetWindow(this);
                var dialogResult = windowDeploy.ShowDialog();

                if (dialogResult == true)
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                        Image = MessageBoxImage.Information,
                        Text = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_Published"),
                        Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"),
                    };

                    Window owner = Window.GetWindow(this);
                    MessageBoxResult dlgResult = WpfMessageBox.Show(owner, ref msgProperties);
                }
            }
        }

        /// <summary>
        /// 处理树展开或关闭
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="Expand"></param>
        private void expandNodes(ObservableCollection<ProjectNode> nodes, bool Expand)
        {
            foreach (ProjectNode node in nodes)
            {
                node.IsExpanded = Expand;
                if (node.Children != null && node.Children.Count > 0)
                {
                    expandNodes(node.Children, Expand);
                }
            }
        }

        /// <summary>
        /// 修复依赖包
        /// </summary>
        /// <param name="newPackage"></param>
        /// <param name="isUninstall"></param>
        private async void repairProjectPackages(List<PackageInfo> repairPackages)
        {
            if (repairPackages.Count > 0)
            {
                StringBuilder repairmsg = new StringBuilder();
                try
                {
                    //Window parentWindow = Window.GetWindow(this);
                    WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_InstallPackage"), App.Current.MainWindow);
                    GlobalActionHandler.PackagePrechange?.Invoke(EventArgs.Empty);

                    foreach (var repairPackage in repairPackages)
                    {
                        WindowLoading.SetMsg(repairPackage.Id);
                        var issuccess = await _projectManager.InstallPackage(repairPackage.Id, repairPackage.Version);

                        if (!issuccess)
                        {
                            repairmsg.Append($"{repairPackage.Id} {repairPackage.Version}");
                            repairmsg.Append(Environment.NewLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new CustomException(LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepairPackages"), ex);
                }
                finally
                {
                    WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
                    GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);

                    var loader = RemoteLoaderHost.GetCurrentInstance();
                    if (loader != null)
                    {
                        loader.Unload();//卸载控件程序域
                    }

                    WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));

                    RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
                    GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);

                    WindowLoading.CloseWindow();

                    if (repairmsg.Length > 0)
                    {
                        var msgProperties1 = new WpfMessageBoxProperties()
                        {
                            Button = MessageBoxButton.OK,
                            ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                            Image = MessageBoxImage.Warning,
                            Text = repairmsg.ToString() + LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepairPackages"),
                            Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_RepairPackages"),
                        };
                        Window owner = Window.GetWindow(this);
                        WpfMessageBox.Show(owner, ref msgProperties1);
                    }
                }
            }
        }

        /// <summary>
        /// 卸载依赖包
        /// </summary>
        /// <param name="uninstallPackages"></param>
        private async void uninstallProjectPackages(PackageInfo uninstallPackage)
        {
            try
            {
                //Window parentWindow = Window.GetWindow(this);
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UninstallPackage"), App.Current.MainWindow);
                GlobalActionHandler.PackagePrechange?.Invoke(EventArgs.Empty);

                await _projectManager.UninstallPackage(uninstallPackage.Id, uninstallPackage.Version);
            }
            catch
            {
                throw;
            }
            finally
            {
                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
                GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);

                var loader = RemoteLoaderHost.GetCurrentInstance();
                if (loader != null)
                {
                    loader.Unload();//卸载控件程序域
                }

                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));
                RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
                GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);

                WindowLoading.CloseWindow();
            }
        }

        #region 命令执行
        private void IsExecuteDefault(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void IsExecuteStatus(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _executionService == null || _executionService.GetCurrentStatus() == ExecuteStatus.Idle;
        }

        private void CmdOpenFolder_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var path = e.Parameter.ToString();
            if (!String.IsNullOrWhiteSpace(path))
            {
                System.Diagnostics.Process.Start("Explorer.exe", path);
            }
        }

        private void CmdRepairPackages_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var repairtPackages = e.Parameter as List<PackageInfo>;
            if (repairtPackages != null)
            {
                repairProjectPackages(repairtPackages);
            }
        }

        private void CmdRepairPackage_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var projectPackage = e.Parameter as ProjectPackage;
            if (projectPackage != null)
            {
                repairProjectPackages(new List<PackageInfo>(1) { new PackageInfo() { Id = projectPackage.Id, Version = projectPackage.Version, TargetFramework = projectPackage.TargetFramework, IsInstalled = false } });
            }
        }

        private void CmdUninstallPackage_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var projectPackage = e.Parameter as ProjectPackage;
            if (projectPackage != null)
            {
                uninstallProjectPackages(new PackageInfo() { Id = projectPackage.Id, Version = projectPackage.Version, TargetFramework = projectPackage.TargetFramework, IsInstalled = false });
            }
        }

        private void CmdNewSequenceScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var forder = e.Parameter as ProjectNode;
            if (forder != null)
            {
                WindowFileName fileNameWindow = new WindowFileName(StaticResource.XamlExtension);
                fileNameWindow.Owner = App.Current.MainWindow;
                var dialogresult = fileNameWindow.ShowDialog();
                if (dialogresult == true)
                {
                    var fileName = fileNameWindow.FileName;
                    ProjectFile file = null;
                    if (_projectManager.CurrentProject.WFLanguage == StaticResource.WorkflowLanguage_vb)
                    {
                        file = _projectManager.CreateXamlFileToProject(forder, fileName, StaticResource.XamlFileTemplateSequence_vb);
                    }
                    else if (_projectManager.CurrentProject.WFLanguage == StaticResource.WorkflowLanguage_cs)
                    {
                        file = _projectManager.CreateXamlFileToProject(forder, fileName, StaticResource.XamlFileTemplateSequence_cs);
                    }

                    if (file != null)
                    {
                        GlobalActionHandler.ScriptShow?.Invoke(new TagEventArgs<Project.ProjectFile>(file));
                    }
                    else
                    {
                        var msgProperties = new WpfMessageBoxProperties()
                        {
                            Button = MessageBoxButton.OK,
                            ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                            Image = MessageBoxImage.Warning,
                            Text = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepeatFilename"),
                            Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"),
                        };
                        Window owner = Window.GetWindow(this);
                        WpfMessageBox.Show(owner, ref msgProperties);
                    }
                }
            }
        }

        private void CmdNewFlowchartScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var forder = e.Parameter as ProjectNode;
            if (forder != null)
            {
                WindowFileName fileNameWindow = new WindowFileName(StaticResource.XamlExtension);
                fileNameWindow.Owner = App.Current.MainWindow;
                var dialogresult = fileNameWindow.ShowDialog();
                if (dialogresult == true)
                {
                    var fileName = fileNameWindow.FileName;
                    ProjectFile file = null;
                    if (_projectManager.CurrentProject.WFLanguage == StaticResource.WorkflowLanguage_vb)
                    {
                        file = _projectManager.CreateXamlFileToProject(forder, fileName, StaticResource.XamlFileTemplateFlowchart_vb);
                    }
                    else if (_projectManager.CurrentProject.WFLanguage == StaticResource.WorkflowLanguage_cs)
                    {
                        file = _projectManager.CreateXamlFileToProject(forder, fileName, StaticResource.XamlFileTemplateFlowchart_cs);
                    }

                    if (file != null)
                    {
                        GlobalActionHandler.ScriptShow?.Invoke(new TagEventArgs<Project.ProjectFile>(file));
                    }
                    else
                    {
                        var msgProperties = new WpfMessageBoxProperties()
                        {
                            Button = MessageBoxButton.OK,
                            ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                            Image = MessageBoxImage.Warning,
                            Text = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepeatFilename"),
                            Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"),
                        };
                        Window owner = Window.GetWindow(this);
                        WpfMessageBox.Show(owner, ref msgProperties);
                    }
                }
            }
        }

        private void CmdImportExistingScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var forder = e.Parameter as ProjectNode;
            if (forder != null)
            {
                var dialogOpen = new VistaOpenFileDialog();
                dialogOpen.Multiselect = true;
                dialogOpen.Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ProjectFolder_Existing_OpenFile");
                if (forder.Name == StaticResource.ProjectSelfFile)
                {
                    dialogOpen.Filter = "(*.xaml)|*.xaml";
                }
                else
                {
                    dialogOpen.Filter = "All files(*.*)|*.*";
                }

                if (dialogOpen.ShowDialog() == true)
                {
                    foreach (var filename in dialogOpen.FileNames)
                    {
                        _projectManager.CopyFileToProject(forder, filename);
                    }
                }
            }
        }
        /// <summary>
        /// 清理图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdClearImages_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.AllScriptSave?.Invoke(EventArgs.Empty);
            var forder = e.Parameter as ProjectNode;
            if (forder != null)
            {
                List<string> imagesList = _projectManager.ClearActivityImages(out int clearNum);
                _projectManager.RefreshImageFolder(imagesList);
                MessageBox.Show(string.Format(LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_ClearImageMessage"), clearNum.ToString()));
            }
        }
        private void CmdShowScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var file = e.Parameter as ProjectFile;
            if (file != null)
            {
                if (file.Extension == StaticResource.XamlExtension)
                {
                    GlobalActionHandler.ScriptShow?.Invoke(new TagEventArgs<Project.ProjectFile>(file));
                }
                else
                {
                    try
                    {
                        System.Diagnostics.Process.Start(file.FullName);//打开其他文件类型文件
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                    }
                }
            }
        }

        private void CmdRenameScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var file = e.Parameter as ProjectFile;
            if (file != null)
            {
                var ext = System.IO.Path.GetExtension(file.Name);
                var fileName = System.IO.Path.GetFileNameWithoutExtension(file.Name);

                WindowFileName fileNameWindow = new WindowFileName(fileName, ext);
                fileNameWindow.Owner = App.Current.MainWindow;
                var dialogresult = fileNameWindow.ShowDialog();
                if (dialogresult == true)
                {
                    var newName = fileNameWindow.FileName + ext;
                    var oldFullName = file.FullName;
                    var isSuccess = _projectManager.RenameNode(file, newName);
                    if (isSuccess)
                    {
                        GlobalActionHandler.ScriptRename?.Invoke(new TagEventArgs<ProjectFile, string>(file, oldFullName));
                    }
                }
            }
        }

        private void CmdDeleteScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var file = e.Parameter as ProjectFile;
            if (file != null)
            {
                var isSuccess = _projectManager.DeleteNode(file);
                if (isSuccess)
                {
                    GlobalActionHandler.ScriptDelete?.Invoke(new TagEventArgs<ProjectFile>(file));
                }
            }
        }
        /// <summary>
        /// 另存为片段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSaveToSnippet_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var file = e.Parameter as ProjectFile;
            if (file != null)
            {
                var targetFolder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "snippets\\Favorites");
                var fileName = System.IO.Path.Combine(targetFolder, file.Name);
                if (FileHelper.CheckFileExisting(fileName))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.YesNo,
                        ButtonYesText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Yes"),
                        ButtonNoText = LocalizationProvider.GetLocalizedString("MessageBox_Button_No"),
                        Image = MessageBoxImage.Question,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Snippets_MessageBox_CoverFile"), file.Name),
                        Title = LocalizationProvider.GetLocalizedString("UCtrlDesignRegion_MsgBox_Caption_CloseApp_ExecutingNotice"),
                    };

                    Window owner = Window.GetWindow(this);
                    MessageBoxResult dlgResult = WpfMessageBox.Show(owner, ref msgProperties);

                    if (dlgResult == MessageBoxResult.No)
                    {
                        return;
                    }
                }

                var isSuccess = _projectManager.SaveToSnippet(file, targetFolder);
                if (isSuccess)
                {
                    GlobalActionHandler.SnippetReload?.Invoke(EventArgs.Empty);
                }
                else
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                        Image = MessageBoxImage.Warning,
                        Text = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_SaveSnippet_Error"),
                        Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"),
                    };
                    Window owner = Window.GetWindow(this);
                    WpfMessageBox.Show(owner, ref msgProperties);
                }
            }
        }
        private void saveToSnippet()
        {

        }
        /// <summary>
        /// 检查并修复活动包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CmdReloadPackage_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                //Window parentWindow = Window.GetWindow(this);
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_InstallPackage"), App.Current.MainWindow);
                GlobalActionHandler.PackagePrechange?.Invoke(EventArgs.Empty);
                var usedAssemblies = getUsedActivity();//已经使用的活动依赖
                var packageInfos = _projectManager.GetDependOnPackageInfos();
                var installedPackageInfos = packageInfos.Where(item => !item.IsInstalled).ToList();
                if (installedPackageInfos != null)//安装项目依赖的活动包
                {
                    foreach (var item in installedPackageInfos)
                    {
                        WindowLoading.SetMsg(item.Id);
                        var issuccess = await _projectManager.InstallPackage(item.Id, item.Version);
                    }
                }
                if (usedAssemblies.Count() > 0)//修复项目依赖中没有的活动
                {
                    foreach (var item in usedAssemblies)
                    {
                        if (!packageInfos.Any(o => o.Id.Contains(item)))
                        {
                            WindowLoading.SetMsg(item);
                            var issuccess = await _projectManager.InstallPackage(item, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CustomException(LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepairPackages"), ex);
            }
            finally
            {
                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
                GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);

                var loader = RemoteLoaderHost.GetCurrentInstance();
                if (loader != null)
                {
                    loader.Unload();//卸载控件程序域
                }

                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));

                RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
                GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);

                WindowLoading.CloseWindow();
            }
        }
        /// <summary>
        /// 检索包到包管理器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdPackageRetrieval_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var package = e.Parameter as ProjectPackage;
            if (package != null)
            {
                WindowPackageManagement managementWindow = new WindowPackageManagement(package.Id);
                managementWindow.Owner = App.Current.MainWindow;
                managementWindow.ShowDialog();
            }
        }

        #endregion

        private void btnCollapse_Click(object sender, RoutedEventArgs e)
        {
            expandNodes(_nodeCollection, false);
        }

        private void btnExpand_Click(object sender, RoutedEventArgs e)
        {
            expandNodes(_nodeCollection, true);
        }
        #region 查找依赖活动
        private void checkSnippetActivity(EventArgs e)
        {
            var msgProperties1 = new WpfMessageBoxProperties()
            {
                Button = MessageBoxButton.OK,
                ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                Image = MessageBoxImage.Warning,
                Text = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_RepairSnippetPackages"),
                Title = LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"),
            };
            Window owner = Window.GetWindow(this);
            WpfMessageBox.Show(owner, ref msgProperties1);
        }
        private void repairSnippetActivity(TagEventArgs<string> e)
        {
            this.Dispatcher.Invoke(async () =>
            {
                await repairSnippetActivity1(e);
            }, System.Windows.Threading.DispatcherPriority.Background);
        }

        private async Task repairSnippetActivity1(TagEventArgs<string> e)
        {
            List<string> usedAssemblies = new List<string>();
            usedAssemblies.AddRange(getUsedAssemblyInXaml(e.Tag));
            usedAssemblies = usedAssemblies.Distinct().ToList();
            bool isChange = false;
            if (usedAssemblies.Count() > 0)//修复项目依赖中没有的活动
            {
                try
                {
                    var packageInfos = _projectManager.GetDependOnPackageInfos();
                    foreach (var item in usedAssemblies)
                    {
                        if (!packageInfos.Any(o => o.Id.Contains(item)))
                        {
                            if (!isChange)
                            {
                                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_InstallPackage"), App.Current.MainWindow);
                                GlobalActionHandler.PackagePrechange?.Invoke(EventArgs.Empty);
                                isChange = true;
                            }
                            WindowLoading.SetMsg(item);

                            var issuccess = await _projectManager.InstallPackage(item, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new CustomException(LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Msg_RepairPackages"), ex);
                }
                finally
                {
                    if (isChange)
                    {
                        WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
                        GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);

                        var loader = RemoteLoaderHost.GetCurrentInstance();
                        if (loader != null)
                        {
                            loader.Unload();//卸载控件程序域
                        }

                        WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));

                        RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
                        GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);

                        WindowLoading.CloseWindow();
                    }
                }
            }
        }
        private IEnumerable<string> getUsedActivity()
        {
            var nodes = _projectManager.CurrentProject.Children;
            var nodefile = nodes.FirstOrDefault(node => node.NodeType == EProjectNodeType.Folder && node.DisplayName == StaticResource.ProjectSelfFile);

            var xamlpaths = nodefile.Children.Select(node => node.FullName);
            List<string> usedassemblies = new List<string>();

            foreach (var xaml in xamlpaths)
            {
                usedassemblies.AddRange(getUsedAssemblyInXaml(xaml));
            }
            usedassemblies = usedassemblies.Distinct().ToList();

            return usedassemblies;
        }
        private IEnumerable<string> getUsedAssemblyInXaml(string filePath)
        {
            List<string> packages = new List<string>();
            XDocument doc = XDocument.Load(filePath);
            foreach (var element in doc.Elements())
            {
                foreach (var attri in element.Attributes())
                {
                    Match match = Regex.Match(attri.Value, @"\;assembly=(.+)$");
                    if (match.Success)
                    {
                        if (match.Groups[1].Value != "System.Activities" && match.Groups[1].Value != "mscorlib")
                            packages.Add(match.Groups[1].Value);
                    }
                }
            }

            return packages.Distinct();
        }
        #endregion
        #region 拖拽 粘贴 复制工程文件
        /// <summary>
        /// 监听按钮 粘贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvProject_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (sender == null)
                return;
            if (e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Control) && e.Key == Key.V)
            {
                var projectNode = this.tvProject.SelectedItem as ProjectNode;

                // GetDataObject获取当前剪贴板上的数据
                IDataObject data = Clipboard.GetDataObject();

                // 将数据与指定的格式进行匹配，返回bool
                if (projectNode.NodeType == EProjectNodeType.File)
                {
                    projectNode = projectNode.Parent;
                }
                if (data.GetDataPresent(DataFormats.FileDrop))
                {
                    // GetData检索数据并指定一个格式
                    string[] fileNames = data.GetData(DataFormats.FileDrop) as string[];
                    string path = _projectManager.GetProjectFolder(projectNode.Name).FullName;
                    foreach (var fileName in fileNames)
                    {
                        var fullName = System.IO.Path.Combine(path, System.IO.Path.GetFileName(fileName));
                        operationFile(fileName, fullName, projectNode);
                    }
                }
            }

            if (e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Control) && e.Key == Key.C)
            {
                var projectNode = this.tvProject.SelectedItem as ProjectNode;
                string[] files = { projectNode.FullName };
                if (files == null || projectNode.NodeType != EProjectNodeType.File) return;
                IDataObject data = new DataObject(DataFormats.FileDrop, files);
                MemoryStream memo = new MemoryStream(4);
                byte[] bytes = new byte[] { (byte)(false ? 2 : 5), 0, 0, 0 };
                memo.Write(bytes, 0, bytes.Length);
                data.SetData("PreferredDropEffect", memo);
                Clipboard.SetDataObject(data, false);
            }
        }
        /// <summary>
        /// 拖拽事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvProject_Drop(object sender, DragEventArgs e)
        {
            if (sender == null)
                return;

            var projectNode = this.tvProject.SelectedItem as ProjectNode;

            if (projectNode.NodeType == EProjectNodeType.File)
            {
                projectNode = projectNode.Parent;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))//项目外拖拽
            {
                string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
                string path = _projectManager.GetProjectFolder(projectNode.Name).FullName;
                foreach (var fileName in fileNames)
                {
                    var fullName = System.IO.Path.Combine(path, System.IO.Path.GetFileName(fileName));
                    operationFile(fileName, fullName, projectNode);
                }
            }
            if (e.Data.GetDataPresent(typeof(ProjectNode)))//项目内拖拽
            {
                var dropProjectNode = e.Data.GetData(typeof(ProjectNode)) as ProjectNode;

                var tvItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
                if (tvItem == null)
                    return;
                if (dropProjectNode.NodeType != EProjectNodeType.File)
                    return;
                var treeNode = tvItem.DataContext as ProjectNode;

                if (treeNode.NodeType == EProjectNodeType.File)
                {
                    treeNode = treeNode.Parent as ProjectFolder;
                }
                if (treeNode.FullName == dropProjectNode.Parent.FullName)
                    return;
                var getFolder = _projectManager.GetProjectFolder(treeNode.Name);
                if (getFolder == null)
                    return;
                string path = getFolder.FullName;
                var fileName = dropProjectNode.FullName;

                var fullName = System.IO.Path.Combine(path, System.IO.Path.GetFileName(fileName));
                operationFile(fileName, fullName, treeNode);
            }
        }

        /// <summary>
        /// 操作文件
        /// </summary>
        /// <param name="fileName">传入的文件</param>
        /// <param name="fullName">已经存在的文件夹文件</param>
        /// <param name="projectNode">要放入的节点</param>
        private void operationFile(string fileName, string fullName, ProjectNode projectNode)
        {
            var ext = System.IO.Path.GetExtension(fileName);
            if (projectNode.Name == StaticResource.ProjectSelfFile)
            {
                if (ext != StaticResource.XamlExtension)
                    return;
            }

            else if (projectNode.Name == StaticResource.ProjectSelfImages)
            {
                if (ext != StaticResource.PngExtension && ext != StaticResource.JpgExtension && ext != StaticResource.JpegExtension)
                    return;
            }

            if (FileHelper.CheckFileExisting(fullName))
            {
                MessageBoxResult dr = MessageBox.Show(fileName + LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_Menu_Item_IsCovered"), LocalizationProvider.GetLocalizedString("UCtrlProjectExplorer_MsgBox_Caption_Publish"), MessageBoxButton.OKCancel, MessageBoxImage.Question);
                if (dr != MessageBoxResult.OK)
                {
                    return;
                }
            }
            _projectManager.CopyFileToProject(projectNode, fileName);
        }
        /// <summary>
        /// 内部拖拽点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvProject_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var projectNode = this.tvProject.SelectedItem as ProjectNode;
                if (projectNode == null)
                    return;
                if (projectNode.NodeType == EProjectNodeType.Folder)
                    return;

                var projectFile = projectNode as ProjectFile;
                if (projectFile != null)
                {
                    if (projectFile.Extension == StaticResource.XamlExtension)
                    {
                        DragDropHost.DragDropScript(projectFile.Name);
                    }
                }

                DataObject dataObject = new DataObject(typeof(ProjectNode), projectNode);
                DragDrop.DoDragDrop(tvProject, dataObject, DragDropEffects.Copy | DragDropEffects.Link);
            }
        }

        #endregion
    }
    public class TreeViewItemHelper
    {
        public static bool GetShowBackground(DependencyObject obj)
        {
            return (bool)obj.GetValue(ShowBackgroundProperty);
        }

        public static void SetShowBackground(DependencyObject obj, bool value)
        {
            obj.SetValue(ShowBackgroundProperty, value);
        }
        public static readonly DependencyProperty ShowBackgroundProperty = DependencyProperty.RegisterAttached(
            "ShowBackground",
            typeof(bool),
            typeof(TreeViewItemHelper),
            new PropertyMetadata(OnShowBackground)
        );

        private static void OnShowBackground(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var item = d as TreeViewItem;
            if (item == null)
                return;
            var node = item.DataContext as ProjectNode;
            if (node == null)
                return;
            if (item != null && (node.NodeType == EProjectNodeType.File || node.NodeType == EProjectNodeType.Package))
                return;
            else
                item.Background = new SolidColorBrush(Colors.Transparent);
        }
    }
}
